# -*- coding: UTF-8 -*-
#-------------------------------------------------------------------------------
# Name:        decorators.py
# Purpose:
#
# Author:      Drago@
#
# Created:     16.09.2009
# Copyright:   (c) Drago@ 2009
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python

from pygs.interfaces import ISecurityInterface
from pygs.logger import logger

def hasRight(rightType):
    """
        Decorator for testing user rights on operation execution
        
        rightType - right type for test.
        serviceProvider - serviceProvider for using.
        
        Description:
            If you using this decorator on method, this method must have
            "token" as first argument and must be applied on IBaseService implementing class.
            
            Decorator check session with specified token on expiration and check rights for user
            on specified operation.
    """
    def checkRights(f):
        def methodWithRightsChecking(instance, token, *args, **kwds):
            # check session on expiration
            logger.debug("Call 'hasRight' decorator: '%s' token test on session expiration." % 
                       (token))
            isSessionExpired = instance.getServiceProvider().implementation(ISecurityInterface).isSessionExpired(token)
            if isSessionExpired:
                faultMessage = ("Session with '%s' token is expired or not exists." % (token))
                logger.debug("Call 'hasRight' decorator: %s." % (faultMessage))
                raise Exception(faultMessage)
                
            # check right
            logger.debug("Call 'hasRight' decorator: '%s' token test on '%s' right type." % 
                       (token, rightType))
            hasRight = instance.getServiceProvider().implementation(ISecurityInterface).hasRigths(token, rightType)
            if hasRight:
                logger.debug("Call 'hasRight' decorator: '%s' token has right for '%s'." % 
                           (token, rightType))
                return f(instance, token, *args, **kwds)
            else:
                faultMessage = ("'%s' token has NOT right for perform '%s'." % (token, rightType))
                logger.debug("Call 'hasRight' decorator: '%s'." % (faultMessage))
                raise Exception(faultMessage)
        return methodWithRightsChecking
    return checkRights
